<template>
  <div>
    <van-list
    v-model="loading"
    :finished="finished"
    finished-text="没有更多了"
    @load="onLoad"
    :error.sync="error"
    error-text="请求失败，点击重新加载"
    :immediate-check= false
    >
        <comment-item 
        :commentInfo="item" 
        v-for="(item,index) in commentInfo" 
        @clickReplay="$emit('clickReplay',$event)"
        :key="index"/>
      <!-- <van-cell v-for="(item,index) in list" :key="index">
      </van-cell> -->
    </van-list>
  </div>
</template>

<script>
import commentItem from './commentItem.vue';
import {getCommentAPI} from '@/api'
export default {
  props:{
    sourceId:{
      type: [Number,String,Object],
      required: true
    },
    commentInfo:{
      type: Array,
      default: ()=>[]
    },
    type:{
      type:String,
      default: 'a',
      validator(value){
        return ['a','c'].includes(value)
      }
    }
  },
  data(){
    return {
      limit: 10,
      offset: null,
      // list: [],
      loading: false,
      finished: false,
      error: false
    }
  },
components: {
  commentItem
},
methods:{
  async onLoad() {
      //获取数据
      try {
        const {data:{data}} = await getCommentAPI({
          //评论类型，a-对文章(article)的评论，c-对评论(comment)的回复
          type: this.type,
          //源id，文章id或评论id
          source: this.sourceId,
          //获取评论数据的偏移量，值为评论id，表示从此id的数据向后取，不传表示从第一页开始读取数据
          offset: this.offset,
          //获取的评论数据个数，不传表示采用后端服务设定的默认每页数据量
          limit: this.limit
        })
        // console.log(data);
        // console.log(data.total_count);
        //将数据赋给list列表
        const {results} = data
        this.commentInfo.push(...results) 
        //将获取到的数据传到父组件中，用于获取评论总数
        this.$emit('getCommentInfo',data)
        //将loading置为false
        this.loading = false
        //判断是否存在数据，存在则继续请求，否则将finished置为true
        if(results.length){
          this.offset = data.last_id
        }
        else {
          this.finished = true
        }
      } catch (error) {
        this.error = true
        this.loading = false
      }
    },
},
created(){
  this.loading = true
  this.onLoad()
}
}
</script>

<style>

</style>